package com.itheima.tlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.tlias.dto.AddClazzDto;
import com.itheima.tlias.dto.CheckClazzDto;
import com.itheima.tlias.dto.UpdateClazzDto;
import com.itheima.tlias.entity.Clazz;
import com.itheima.tlias.exception.BizException;
import com.itheima.tlias.mapper.ClazzMapper;
import com.itheima.tlias.mapper.StudentMapper;
import com.itheima.tlias.service.ClazzService;
import com.itheima.tlias.vo.ClazzListVo;
import com.itheima.tlias.vo.PageBean;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    @Autowired
    private ClazzMapper clazzMapper;
    @Autowired
    private StudentMapper studentMapper;

    @Override

    public PageBean<ClazzListVo> clazzPage(CheckClazzDto clazzDto) {
        PageHelper.startPage(clazzDto.getPage(), clazzDto.getPageSize());
        Page<ClazzListVo> clazzListVos = clazzMapper.clazzPage(clazzDto);
        return new PageBean<>(clazzListVos.getTotal(), clazzListVos.getResult());
    }

    @Override
    public void addClazz(AddClazzDto dto) {
        Clazz clazz = new Clazz();
        BeanUtils.copyProperties(dto, clazz);
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClazz(clazz);
    }


    @Override
    public void deleteClazz(Integer id) {

        if (!CollectionUtils.isEmpty(studentMapper.studentByClazzId(id))){
            throw new BizException("该班级中还有学生，无法删除");
        }
            clazzMapper.deleteClazz(id);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    @Override
    public void updateClazz(UpdateClazzDto dto) {
        Clazz clazz = new Clazz();
        BeanUtils.copyProperties(dto, clazz);
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }

    @Override
    public List<Clazz> students() {
        return clazzMapper.students();
    }


}
